#include "layer.h"

Layer::Layer(int rank)
	: rank {rank}
{}

void Layer::cleanup()
{
	if (player_set && player->render_data.texture != nullptr)
		SDL_DestroyTexture(player->render_data.texture);

	for (Entity& e : entities)
		if (e.render_data.owns_texture && e.render_data.texture != nullptr)
			SDL_DestroyTexture(e.render_data.texture);

	for (Drawable& d : drawables)
		if (d.render_data.owns_texture && d.render_data.texture != nullptr)
			SDL_DestroyTexture(d.render_data.texture);

	for (Button& b : buttons)
		if (b.render_data.owns_texture && b.render_data.texture != nullptr)
			SDL_DestroyTexture(b.render_data.texture);
}

void Layer::update(State& state, std::vector<Layer>& layers, bool pressed_keys[], int& camera_x, int& camera_y)
{
	if (has_player()) {
		player->update(state, pressed_keys, camera_x, camera_y);
		for (auto& l : layers) {
			for (auto& e : l.entities) {
				Sprite& s = e.multi_sprite.selected();
				if (s.collides &&
					player->pos.x < e.pos.x + e.pos.w &&
					player->pos.x +	player->pos.w > e.pos.x &&
					player->pos.y < e.pos.y + e.pos.h &&
					player->pos.y +	player->pos.h > e.pos.y) {
					player->undo(state, pressed_keys, camera_x, camera_y);
					break;
				}
			}
		}
	}

	for (auto& e : entities)
		e.update(state, pressed_keys, camera_x, camera_y);

	for (auto& d : drawables)
		d.update(state, pressed_keys, camera_x, camera_y);

	for (auto& b : buttons)
		b.update(state, pressed_keys, camera_x, camera_y);
}

void Layer::render(SDL_Renderer *renderer)
{
	for (auto& e : entities)
		e.render(renderer);

	if (player_set)
		player->render(renderer);

	for (auto& d : drawables)
		d.render(renderer);

	for (auto& b : buttons)
		b.render(renderer);
}